package com.agileai.esb.smc.controller.sysres;

import java.util.List;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sysres.SysFuncBaseTreeManage;
import com.agileai.esb.smc.bizmoduler.sysres.SysUserManage;
import com.agileai.hotweb.controller.core.TreeSelectHandler;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class SysFuncBaseTreeHandler
        extends TreeSelectHandler {
	
    public SysFuncBaseTreeHandler() {
        super();
        this.serviceId = buildServiceId(SysFuncBaseTreeManage.class);
        this.isMuilSelect = true;
        this.checkRelParentNode = true;
    }
    
	public ViewRenderer prepareDisplay(DataParam param){
		this.setAttributes(param);
		invisiableCheckBoxIdList.add("C8CD0F2E-FE4B-4EDA-9C0D-858B338BF985");
		TreeBuilder treeBuilder = provideTreeBuilder(param);
		TreeModel topTreeModel = treeBuilder.buildTreeModel();
		String pickTreeSyntax = null;
		if (isMuilSelect){
			pickTreeSyntax = getMuliPickTreeSyntax(topTreeModel, new StringBuffer());
		}else{
			pickTreeSyntax = getTreeSyntax(topTreeModel,new StringBuffer());	
		}
		String checkedIds = getAuthCheckeds(param);
		this.setAttribute("pickTreeSyntax", pickTreeSyntax);
		this.setAttribute("checkedIds", checkedIds);
		return new LocalRenderer(getPage());
	}
	
    protected TreeBuilder provideTreeBuilder(DataParam param) {
        List<DataRow> records = getService().queryPickTreeRecords(param);
        TreeBuilder treeBuilder = new TreeBuilder(records, "FUNC_ID",
                                                  "FUNC_NAME", "FUNC_PID");
        return treeBuilder;
    }
    
	private String getAuthCheckeds(DataParam param) {
		List<DataRow> dataRowList = lookupService(SysUserManage.class)
				.findAuthCheckeds(param);
		String checkedIds = "";
		for (int i = 0; i < dataRowList.size(); i++) {
			DataRow dataRow = dataRowList.get(i);
			String funcId = dataRow.stringValue("AUTH_FUNC_ID");
			checkedIds += funcId + ",";
		}
		return checkedIds;
	}

	protected SysFuncBaseTreeManage getService() {
        return (SysFuncBaseTreeManage) this.lookupService(this.getServiceId());
    }
	
}
